package dbinit;
import java.util.List;
import java.util.Iterator ;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import core.product.model.ProductType;
import core.util.HibernateCoreUtil;

public class InitProductType 
{
	public static ProductType getProductTypeByUuid(Long uuid)
	{
		ProductType pt = null ;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try 
		{
				transaction = session.beginTransaction();
				pt = (ProductType) session.get(ProductType.class, uuid);
				transaction.commit();
		}
		catch (HibernateException e) 
		{
			// TODO: handle exception
			transaction.rollback();
			e.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return pt ;
	}
	
	public static Long createOrGetUuidByName(String name)
	{
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		Long uuid = null ;
		ProductType pt = null ;
		try
		{
			transaction = session.beginTransaction();
			List <ProductType> pts = session.createQuery("from ProductType pt where pt.productType='"+name+"'").list();
			 if(pts.size() == 0)
			 {
				uuid = doinit(name);
			 }
			 else
			 {
				 Iterator <ProductType> ptsItr = pts.iterator(); 
				 while(ptsItr.hasNext())
				 {
					 pt = ptsItr.next() ;
					 break ;
				 }
				 uuid = pt.getUuid();
			 }
		}
		catch(HibernateException e)
		{
			e.printStackTrace();
		}
		return uuid;
	}
	
	public static Long doinit(String productType)
	{
		Transaction transaction = null;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		
		ProductType pt = new ProductType();
		pt.setProductType(productType);
		Long uuid = null ;
		try
		{
			transaction = session.beginTransaction();
		    uuid = (Long)session.save(pt);
			transaction.commit();
		}
		catch(HibernateException he)
		{
			he.printStackTrace();
		}
		return uuid ;
	}
}
